package com.basis.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.openbravo.base.session.OBPropertiesProvider;

public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 7618658514199005769L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		request.setCharacterEncoding("utf-8");

	    String path = OBPropertiesProvider.getInstance().getOpenbravoProperties().getProperty("attach.path") + "/fileImport/";
		
		String maxSize = request.getParameter("maxSize");
		FileUploadService fileUploadService = new FileUploadService();
		fileUploadService.setStoragePath(path);
		fileUploadService.setRetainFileName(true);
		fileUploadService.setServletContext(getServletContext());
		if (maxSize != null) {
			fileUploadService.setMaxSize(Long.parseLong(maxSize));
		}
		JSONObject json = new JSONObject();
		try {
			json.put("success", true);
			List<File> files = fileUploadService.getFilesInLocal(request);
			for (File file : files) {
				json.put("name", file.getName());
				json.put("size", file.length());
				json.put("type", file.getContentType());
				json.put("missing", file.isMissing());
				json.put("allowed", file.isAllowed());
				json.put("path", file.getPath());
			}
		} catch (Exception e) {
			try {
				json.put("success", false);
				json.put("msg", e.getMessage());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
		}
		PrintWriter out = response.getWriter();
		out.println(json.toString());
		out.flush();
		out.close();
	}
}
